package com.czl.module_storehouse.activity.remand.damage;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;

import com.czl.base.data.bean.tengyun.LocatListBean;
import com.czl.base.data.bean.tengyun.RecordRemandBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.util.SpHelper;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.utils.ParcelHelper;
import com.czl.module_base.utils.RxRegUtils;
import com.czl.module_service.event.DamageRegisBackEvent;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.base.BaseOperationLocationActivity;
import com.czl.module_storehouse.databinding.ActivityDamageRegisBinding;
import com.czl.module_storehouse.event.DamageRegisEvent;
import com.czl.module_storehouse.event.RemandSelectedOrderEvent;
import com.czl.module_storehouse.event.SortEvent;
import com.czl.module_storehouse.mvp.presenter.StorehouseLocationPresenter;
import com.czl.module_storehouse.mvp.view.StorehouseLocationView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author xubin
 */
public class DamageRegisActivity extends BaseOperationLocationActivity<ActivityDamageRegisBinding> implements StorehouseLocationView {

    private int mMaxNum;
    private int mLostNum;
    private int mDamageNum;
    private SortBean mSortBean;
    private String mLastLocation;
    @InjectPresenter
    StorehouseLocationPresenter mStorehouseLocationPresenter;

    @Override
    protected ActivityDamageRegisBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityDamageRegisBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mToolBinding.toolbarContentTitle.setText("损坏登记");
        binding.tvLocation.setOnClickListener(v -> getStorehouseLocatList(true));
        binding.textConfirm.setOnClickListener(v -> submit());
        binding.textAddLose.setOnClickListener(v -> addLose());
        binding.textRemoveLose.setOnClickListener(v -> removeLose());
        binding.layoutBroken.textRemove.setOnClickListener(v -> remove());
        binding.layoutBroken.textAdd.setOnClickListener(v -> add());
        EventBus.getDefault().register(this);
        initListener();
    }

    private void setLocationEnable() {
        if (mLostNum > 0 && mDamageNum == 0) {
            binding.tvLocation.setEnabled(false);
            binding.tvLocation.setVisibility(View.GONE);
        } else {
            binding.tvLocation.setEnabled(true);
            if (TextUtils.isEmpty(mLastLocation)) {
                binding.tvLocation.setText("选择存放位置");
            } else {
                binding.tvLocation.setText(mLastLocation);
            }
            binding.tvLocation.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(DamageRegisEvent event) {
        SortBean sortBean = event.getSortBean();
        if (sortBean == null) {
            return;
        }
        mSortBean = ParcelHelper.copy(sortBean);
        binding.tvSortName.setText(sortBean.getSortName());
        //待归还数量
        int remandNum = sortBean.getRemandNum() + (sortBean.getExcNum() == null ? 0 : sortBean.getExcNum());
        //完好数量
        int stockNum = sortBean.getGoodNum(SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID));
        mMaxNum = remandNum - stockNum;
        binding.tvReturnNum.setText(getString(R.string.wait_return_num_placeholder, remandNum));
        binding.tvIntactNum.setText(getString(R.string.intact_num_placeholder, stockNum));
        binding.etDamageComment.setText(sortBean.getDamageComment());
        binding.tvLocation.setText(mSortBean.getExcLocatName());
        int damageNum = 0;
        if (mSortBean.getExcNum() != null) {
            if (mSortBean.getExcLossesNum() != null) {
                damageNum = mSortBean.getExcNum() - mSortBean.getExcLossesNum();
            } else {
                damageNum = mSortBean.getExcNum();
            }
        }
        binding.layoutBroken.tvQuantity.setText(String.valueOf(damageNum));
        binding.tvQuantityLose.setText(String.valueOf(mSortBean.getExcLossesNum() == null ? 0 : mSortBean.getExcLossesNum()));
        mDamageNum = damageNum;
        if (mSortBean.getExcLossesNum() != null) {
            mLostNum = mSortBean.getExcLossesNum();
        }
        mLastLocation = sortBean.getExcLocatName();
        setLocationEnable();
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(RemandSelectedOrderEvent event) {
        SortBean sortBean = event.getSortBean();
        if (sortBean == null) {
            return;
        }
        mSortBean = ParcelHelper.copy(sortBean);

        binding.tvSortName.setText(sortBean.getSortName());
        RecordRemandBean recordRemandBean = event.getRecordRemandBean();
        if (recordRemandBean == null) {
            return;
        }
        //完好数量
        int returnNumInt = recordRemandBean.getReturnNumInt();
        //待归还数量
        int remandNum = recordRemandBean.getNeedReturnNumInt();
        mMaxNum = remandNum - returnNumInt;
        binding.tvReturnNum.setText(getString(R.string.wait_return_num_placeholder, remandNum));
        binding.tvIntactNum.setText(getString(R.string.intact_num_placeholder, returnNumInt));
        binding.etDamageComment.setText(recordRemandBean.getDamageComment());
        binding.tvLocation.setText(mSortBean.getExcLocatName());

        int damageNum = recordRemandBean.getExcNumInt() - recordRemandBean.getExcLossesNum();
        binding.layoutBroken.tvQuantity.setText(String.valueOf(damageNum));
        binding.tvQuantityLose.setText(String.valueOf(recordRemandBean.getExcLossesNum() == null ? 0 : recordRemandBean.getExcLossesNum()));
        mDamageNum = damageNum;
        mLostNum = recordRemandBean.getExcLossesNumInt();
        setLocationEnable();

    }

    protected void initListener() {

        binding.layoutBroken.tvQuantity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                if (RxRegUtils.checkDigit2(text)) {
                    int num = Integer.parseInt(text);
                    if (num > (mMaxNum - mLostNum)) {
                        num = mMaxNum - mLostNum;
                        mDamageNum = num;
                        binding.layoutBroken.tvQuantity.setText(String.valueOf(num));
                    } else if (num < 0) {
                        num = 0;
                        mDamageNum = num;
                        binding.layoutBroken.tvQuantity.setText(String.valueOf(num));
                    } else {
                        mDamageNum = num;
                    }
                    binding.layoutBroken.tvQuantity.setSelection(binding.layoutBroken.tvQuantity.getText().length());

                    setLocationEnable();
                }
            }
        });

        binding.tvQuantityLose.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                if (RxRegUtils.checkDigit2(text)) {
                    int num = Integer.parseInt(text);
                    if (num > (mMaxNum - mDamageNum)) {
                        num = mMaxNum - mDamageNum;
                        mLostNum = num;
                        binding.tvQuantityLose.setText(String.valueOf(num));
                    } else if (num < 0) {
                        num = 0;
                        mLostNum = num;
                        binding.tvQuantityLose.setText(String.valueOf(num));
                    } else {
                        mLostNum = num;
                    }
                    binding.tvQuantityLose.setSelection(binding.tvQuantityLose.getText().length());

                    setLocationEnable();
                }
            }
        });
    }

    @Override
    protected boolean callBackModel(LocatListBean bean) {
        boolean call = super.callBackModel(bean);
        if (!call) {
            showToast("该库位已添加");
            return false;
        }
        binding.tvLocation.setText(bean.getStorehouseLocatName());
        mLastLocation = bean.getStorehouseLocatName();
        if (mSortBean != null) {
            mSortBean.setExcLocatId(bean.getStorehouseLocatId());
        }
        if (mSortBean != null) {
            mSortBean.setExcLocatName(bean.getStorehouseLocatName());
        }
        return true;
    }

    private void submit() {
        if (mSortBean == null) {
            return;
        }
        int excNum = 0;
        String textDamage = binding.layoutBroken.tvQuantity.getText().toString();
        if (RxRegUtils.checkDigitPositive(textDamage)) {
            excNum += Integer.parseInt(textDamage);
        }
        String textLose = binding.tvQuantityLose.getText().toString();
        if (RxRegUtils.checkDigitPositive(textLose)) {
            excNum += Integer.parseInt(textLose);
            mSortBean.setExcLossesNum(Integer.parseInt(textLose));
        }
        mSortBean.setExcNum(excNum);
        mSortBean.setDamageComment(binding.etDamageComment.getText().toString());
        EventBus.getDefault().postSticky(new SortEvent(mSortBean));
        LiveEventBus.get(DamageRegisBackEvent.class).post(new DamageRegisBackEvent(mSortBean));
        finish();
    }

    private void remove() {
        String text = binding.layoutBroken.tvQuantity.getText().toString();
        if (text == null || text.isEmpty()) {
            text = "0";
        }
        if (RxRegUtils.checkDigitPositive(text)) {
            int num = Integer.parseInt(text);
            if (num <= 0) {
                num = 0;
            } else {
                num--;
            }
            binding.layoutBroken.tvQuantity.setText(String.valueOf(num));
        }
    }

    private void add() {
        String text = binding.layoutBroken.tvQuantity.getText().toString();
        if (text == null || text.isEmpty()) {
            text = "0";
        }
        if (RxRegUtils.checkDigitPositive(text)) {
            int num = Integer.parseInt(text);
            if (num >= (mMaxNum - mLostNum)) {
                num = mMaxNum - mLostNum;
            } else {
                num++;
            }
            binding.layoutBroken.tvQuantity.setText(String.valueOf(num));
        }
    }

    private void removeLose() {
        String text = binding.tvQuantityLose.getText().toString();
        if (text == null || text.isEmpty()) {
            text = "0";
        }
        if (RxRegUtils.checkDigitPositive(text)) {
            int num = Integer.parseInt(text);
            if (num <= 0) {
                num = 0;
            } else {
                num--;
            }
            binding.tvQuantityLose.setText(String.valueOf(num));
        }
    }

    private void addLose() {
        String text = binding.tvQuantityLose.getText().toString();
        if (text == null || text.isEmpty()) {
            text = "0";
        }
        if (RxRegUtils.checkDigitPositive(text)) {
            int num = Integer.parseInt(text);
            if (num >= (mMaxNum - mDamageNum)) {
                num = mMaxNum - mDamageNum;
            } else {
                num++;
            }
            binding.tvQuantityLose.setText(String.valueOf(num));
        }
    }

    @Override
    protected StorehouseLocationPresenter getLocationPresenter() {
        return mStorehouseLocationPresenter;
    }
}
